//
//  HMNetworkTools.swift
//  3.Swift中网络的封装
//
//  Created by heima on 16/4/8.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import AFNetworking

//定义结构体封装接口,如果接口变了,那么只需要改变借口即可,内部数据不再需要改动

struct API {

    //正式发布阶段需要访问的服务器主机名
    static let onlineHost = "https://api.weibo.com/"
    //内测阶段用,这样就可以写一套代码
    static let testHost = "http://xxx."
    static let access_token = "oauth2/access_token"

    static let usersShow = "2/users/show.json"
    /// 微博接口
    static let home_timeline = "2/statuses/home_timeline.json"
    //发布微博的借口
    static let uploadStatus = "2/statuses/update.json"
    static let uploadImage = "https://upload.api.weibo.com/2/statuses/upload.json"
}


//swift 中的枚举
enum HMHttpMethods: String {
    case POST = "POST"
    case GET = "GET"
}

/// MARK:网络请求的核心方法
class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HMNetworkTools = {

        let baseURL = NSURL(string: API.onlineHost)

        let tools = HMNetworkTools(baseURL: baseURL)

        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tools
    }()


    //封装所有的网络请求方法 所有的网络请求都是通过这个方法和 AFN进行联系
    func request(method: HMHttpMethods,urlString: String, parameters: AnyObject?, finished: (result: AnyObject?, error: NSError?) -> ()) {

        //swift中就不能够使用利用协议 欺骗Xcode
        //为了达到封装的目的 可以将相同的闭包 抽取出来,当做参数传递给AFN框架
        let success =  { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            //执行成功的回调
            finished(result: result, error: nil)
        }

        //定义失败的回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            //执行失败的回调
            finished(result: nil, error: error)
        }


        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }

    }


}

// MARK: - 将请求用户数据的方法封装到网络工具类中来
extension HMNetworkTools{

    func loadAccessToken(code:String,finished: (result: AnyObject?, error: NSError?) -> ()){

        let urlString = API.access_token

        let param = [
            "client_id":"350157411",
            "client_secret":"51f0aa2f95517eef9a11888af1bcabdc",
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":"https://movie.douban.com/"
        ]

        request(.POST, urlString: urlString, parameters: param, finished: finished)

    }


    func loadUserInfo(tockenResult:AnyObject,finished: (result: AnyObject?, error: NSError?) -> ()){

        //将AnyObject转为字典
        let dictResult = tockenResult as! [String:AnyObject]

        //根据键获取值
        let access_token = dictResult["access_token"]! as! String

        let uid = dictResult["uid"]!

        //读取用户信息借口的url
        let urlString = API.usersShow

        //请求所需要的参数
        let param = ["access_token":access_token,"uid":uid]

        request(.GET, urlString: urlString, parameters: param, finished: finished)
    }


    //需要返回请求的数据
    //max_id 	false 	int64 	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    func loadWeiBoInfo(token:String,since_id :Int64,var max_id:Int64,finished: (result: AnyObject?, error: NSError?) -> ()){

        var param = ["access_token":token]

        if max_id > 0 {

            max_id = max_id - 1

            param["max_id"] = "\(max_id)"

        }

        if since_id > 0 {

            param["since_id"] = "\(since_id)"

        }

        request(.GET, urlString: API.home_timeline, parameters: param, finished: finished)
    }


    //MARK:发布文字微博
    /*
    access_token 	true 	string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
    status 	true 	string 	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
    */



    func uploadStatus(access_token:String,status:String,images:[UIImage]? = nil,finished: (result: AnyObject?, error: NSError?) -> ()){

        let param = ["access_token":access_token,"status":status]
        
        
        if let imgs = images where imgs.count > 0{

            POST(API.uploadImage, parameters: param, constructingBodyWithBlock: { (formData) -> Void in

                    let data = UIImagePNGRepresentation(imgs.first!)!

                    formData.appendPartWithFileData(data, name: "pic", fileName: "xxx\(index)", mimeType: "image/png")

                }, progress: nil, success: { (_, result) -> Void in
                    //上传成功
                    finished(result: result, error: nil)

                }, failure: { (_, error) -> Void in
                    //上传失败
                    finished(result: nil, error: error)
            })

        }else{
            request(.POST, urlString: API.uploadStatus, parameters: param, finished: finished)
            
        }
    }
}
